/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.HibernateException;

import domain.pojo.Client;
import util.HibernateUtil;

/**
 *
 * @author lion
 */
public class ClientDaoImpl extends ClientDao {

    private Session session = null;

    public ClientDaoImpl() {
        session = HibernateUtil.getSessionFactory().openSession();
    }

    @Override
    public List<Client> getClients() {
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            List<Client> clients = session.createQuery("from Client").list();
            transaction.commit();
            return clients;
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Client getClient(int clientId) {
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Client client = (Client) session.get(Client.class, clientId);
            transaction.commit();
            return client;
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Integer insertClient(Client client) {
        Transaction transaction = null;
        Integer clientId = null;
        try {
            transaction = session.beginTransaction();
            clientId = (Integer) session.save(client);
            transaction.commit();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return clientId;
    }

    @Override
    public boolean deleteClient(Client client) {
        Transaction transaction = null;
        boolean result = false;
        try {
            transaction = session.beginTransaction();
            session.delete(client);
            transaction.commit();
            result = true;
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public boolean updateClient(Client client) {
        Transaction transaction = null;
        boolean result = false;
        try {
            transaction = session.beginTransaction();
            session.update(client);
            transaction.commit();
            result = true;
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return true;
    }
}
